package com.teliasonera.crm.testing;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

public class LoginPage extends CRMPage {

    private static final String LOGIN_ERROR = "//div[@class='login-messages']/span[@class='portlet-msg-error']";
    private static final String LOGIN_USERNAME = "_58_login";
    private static final String LOGIN_PASSWORD = "_58_password";
    private static final String LOGIN_BUTTON = "image";

    public LoginPage(WebDriver driver) {
        super(driver);
        
        if (!driver.findElement(By.xpath(LOGIN_PAGE)).isDisplayed()) {
            throw new IllegalStateException("Could not find login form in " + driver.getTitle() + " / " + driver.getCurrentUrl());
        }
    }

    public HomePage attemptLogin(String username, String password) {
        
        try {
            
            driver.findElement(By.id(LOGIN_USERNAME)).sendKeys(username);
            driver.findElement(By.id(LOGIN_PASSWORD)).sendKeys(password);
            driver.findElement(By.name(LOGIN_BUTTON)).click();
            
        } catch (Exception e) {
            log(e.getMessage());
            refresh();
        }
        
        /*
         * @todo add login error handling
         * 
         */
        return new HomePage(driver);
        
    }
}